﻿using MengRan.Models.index;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MengRan.Controllers
{
    [ApiController]
    [Route("api/[Controller]/[action]")]
    public class AuthenticateController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public AuthenticateController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [AllowAnonymous]
        [HttpPost]
        public IActionResult Login([FromBody] user loginDto)
        {
            //User Authentication
            if (string.IsNullOrWhiteSpace(loginDto.username) || string.IsNullOrWhiteSpace(loginDto.password))
            {
                return BadRequest("Email or Password can not be empty");
            }

            //Generate Token
            var token = GenerateJWT();

            return Ok(token);
        }

        private string GenerateJWT()
        {
            // 1. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 2. 定义需要使用到的Claims
            var claims = new[]
            {
                //sub user Id
                new Claim(JwtRegisteredClaimNames.Sub, "Duke"),
                //role Admin
                new Claim(ClaimTypes.Role, "Admin"),
            };

            // 3. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上组件，生成token
            var token = new JwtSecurityToken(
                _configuration["JWT:Issuer"],    //Issuer
                _configuration["JWT:Audience"],  //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddDays(1),         //expires
                signingCredentials
            );
            // 6. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return jwtToken;
        }
    }
}
